package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.BlogDao;
import model.Blog;
import model.User;
import utils.StringUtil;
import utils.UserUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * 功能描述
 *
 * @author wileda
 * @date 2023/04/09  15:31
 */
@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 编码格式
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json; charset=utf-8");
        // 获取参数值
        String blogId = req.getParameter("blogId");
        String json = null;
        BlogDao blogDao = new BlogDao();
        // 判断参数是否为空，如果为空就表示没有传
        if (StringUtil.isEmpty(blogId)) {
            // 查询博客列表
            List<Blog> blogs = blogDao.selectAll();
            if (blogs == null) {
                // 防止返回一个null字符串，空集全的时候应该返回[]
                blogs =  new ArrayList<Blog>();
            }
            json = objectMapper.writeValueAsString(blogs);
        } else {
            // 根据Id查询博客详情
            Blog blog = blogDao.selectById(Long.valueOf(blogId));
            json = objectMapper.writeValueAsString(blog);
        }

        resp.getWriter().write(json);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 编码格式
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=utf-8");
        //获取参数
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        //非空校验
        if(StringUtil.isEmpty(title)||StringUtil.isEmpty(content)){
            resp.getWriter().write("标题或者内容不能为空");
            return;
        }
        User user = UserUtil.checkUserLoginStatus(req);
        //非空校验
        if(user == null){
            resp.sendRedirect("blog_login.html");
            return;
        }
        //构件blog对象
        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        blog.setCreateTime(new Timestamp(System.currentTimeMillis()));
        //设置用户ID
        blog.setUserId(user.getId());

        //写入数据库
        BlogDao blogDao = new BlogDao();
        int result = blogDao.insert(blog);
        if(result != 1){
            resp.getWriter().write("写入博客失败");
        }else {
            //跳转到列表页
            resp.sendRedirect("blog_list.html");
        }
    }

    /**
     *  实现删除博客逻辑
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 编码格式
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=utf-8");

        //获取当前用户信息
        User user = UserUtil.checkUserLoginStatus(req);
        if(user == null){
            resp.setStatus(403);
            resp.getWriter().write("没有权限");
            return;
        }


        //获取参数
        String blogId = req.getParameter("blogId");
        //非空校验
        if(StringUtil.isEmpty(blogId)){
            resp.setStatus(500);
            resp.getWriter().write("没有参数");
            return;
        }

        BlogDao blogDao = new BlogDao();
        //获取博客详情
        Blog blog = blogDao.selectById(Long.valueOf(blogId));
        if(blog == null){
            resp.setStatus(500);
            resp.getWriter().write("没有对应的博客");
            return;
        }
        //判断当前用户是不是作者
        if(user.getId() != blog.getUserId()){
            resp.setStatus(403);
            resp.getWriter().write("不是作者，没有权限");
            return;
        }

        //通过DAO删除博客
        int result = blogDao.delete(Long.valueOf(blogId));
        if(result == 1){
            resp.getWriter().write("删除成功");
        }else {
            resp.setStatus(500);
            resp.getWriter().write("删除失败");
        }
    }
}
